/**
 * NewsInfoServiceImpl.java
 * @author
 * 作者 屈甲康 
 */
package org.jackysoft.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jackysoft.entity.nosql.NewsCatalog;
import org.jackysoft.entity.nosql.NewsInfo;
import org.jackysoft.service.AbstractNoSqlServiceImpl;
import org.jackysoft.service.NewsCatalogService;
import org.jackysoft.service.NewsInfoService;
import org.jackysoft.util.IOUtils;
import org.jackysoft.util.Office2PDF;
import org.jackysoft.util.PDFConveter;
import org.jackysoft.util.ReportType;
import org.jackysoft.util.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.itextpdf.text.DocumentException;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

@Service
public class NewsInfoServiceImpl extends
		AbstractNoSqlServiceImpl<NewsInfo> implements NewsInfoService {

	protected static final Log log = LogFactory
			.getLog(NewsInfoServiceImpl.class);

	private NewsCatalogService catalogService;
	/**
	 * 
	 */
	private static final long serialVersionUID = -1926580573197540573L;

	public NewsInfoServiceImpl() {
		this.type = NewsInfo.class;
	}

	@Override
	public Collection<NewsInfo> gets(int start, int size)
			throws DataAccessException {

		DBObject sort = new BasicDBObject("createDate",-1);
		return super.gets(start, size, sort);

	}

	@Override
	public Collection<NewsInfo> gets(int start, int size,
			String catalog) throws DataAccessException {
		
	
		if(catalog==null)return Lists.newArrayList();
		DBObject query = new BasicDBObject("catalog",catalog);
		DBObject sort = new BasicDBObject("createDate",-1);
		return this.query(start, size, query, sort);
	}


	@Override//sdfsdf
	public void create(String catalog,Date createDate, File upLoad, String upLoadFileName)
			throws IOException, InterruptedException, ExecutionException,
			DocumentException  {
		 byte[] data = IOUtils.toByteArray(upLoad);
		 append(catalog, createDate, data, upLoadFileName);
		
	}

	protected void append(String catalog, Date createDate, byte[] data,
			String upLoadFileName) throws InterruptedException, ExecutionException, IOException, DocumentException{		
		String path = File.separator + "attachment" + File.separator;
		String ext = StringUtils.splitPostFileName(upLoadFileName);
		String name = "";
		String relativeUrl = "/attachment/";
		createDate = createDate==null?new Date():createDate;
		NewsInfo bean = new NewsInfo();
		if ("doc".equalsIgnoreCase(ext)) {
			
			log.info("开始传送文件 :" + upLoadFileName);
			Office2PDF wpf = new Office2PDF(config.getPdfServer(),
					config.getPdfServerPort(), ext, data);
			ExecutorService executor = Executors.newSingleThreadExecutor();
			Future<String> future = executor.submit(wpf);
			name = future.get() + ".pdf";
			executor.shutdown();
			relativeUrl += name;
			
			bean.setCreateDate(createDate);
			bean.setCatalog(catalog);
			bean.setName(upLoadFileName);
			String fullName = path + name;
			bean.setWebPrefix(System.getProperty("base"));
			bean.setFullPath(fullName);
			bean.setRelativeUrl(relativeUrl);
			
			log.info("传送文件 :" + upLoadFileName + " 完成" + ", 文件名: " + name);
		} else if ("xls".equalsIgnoreCase(ext)) {
			bean=parse(catalog,createDate, data);
		} else if("pdf".equalsIgnoreCase(ext)){
		
			name = UUID.randomUUID().toString() + ".pdf";
			String fullName = path + name;			
			relativeUrl += name;
			bean.setCreateDate(createDate);
			bean.setCatalog(catalog);
			bean.setName(upLoadFileName);			
			bean.setFullPath(fullName);
			bean.setWebPrefix(System.getProperty("base"));
			bean.setRelativeUrl(relativeUrl);
			String diskPath = System.getProperty("appBase")+fullName;
			IOUtils.saveFile(data, new File(diskPath));
			
		}
		create(bean);
        
		
		
	}
	
	@Override
	public void create(String catalog, Date createDate, InputStream input,
			String upLoadFileName) throws InterruptedException,
			ExecutionException, IOException, DocumentException {
		byte[] data  = IOUtils.toByteArray(input);
		this.append(catalog, createDate, data, upLoadFileName);		
	}
	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jackysoft.service.AbstractNoSqlServiceImpl#findAll(int, int)
	 */
	@Override
	protected List<NewsInfo> findAll(int start, int size) {
		DBObject sort = new BasicDBObject("createDate",-1);
	    List<NewsInfo> lists = Lists.newArrayList();
	    lists.addAll(gets(start, size, sort));
		return lists;
	}

	@Resource
	public void setCatalogService(NewsCatalogService catalogService) {
		this.catalogService = catalogService;
	}

	

	protected NewsInfo parse(String catalog, Date createDate, byte[] data) throws InterruptedException, ExecutionException,  IOException, DocumentException {
		String path = File.separator + "attachment" + File.separator;
		String name = "";
		String relativeUrl = "/attachment/";
		
		name = UUID.randomUUID().toString() + ".pdf";
		relativeUrl += name;
		String fontHome = System.getenv("WINDIR") + "\\fonts\\SIMFANG.TTF";
		String pdfname = System.getProperty("appBase") + "\\attachment\\"
				+ name;
		NewsCatalog cat = catalogService.get(catalog);		
		// "产值，品种跟进表";// "生产日报";
		String ptitle = "";
		ReportType rtype = null;		
		if (("重点品种").equals(cat.getName())) {
			rtype = ReportType.重点品种;
		    SimpleDateFormat fmt = new SimpleDateFormat();
			fmt.applyPattern("yyyy年MM月dd日" + rtype.toString()+"进展看板");			
			ptitle = fmt.format(createDate);

		} else if ("生产日报".equals(cat.getName())) {
			rtype = ReportType.生产日报;
			SimpleDateFormat fmt = new SimpleDateFormat();
			fmt.applyPattern("yyyy年MM月dd日" + rtype.toString());
			ptitle = fmt.format(createDate);
			
		} else if("生产月报".equals(cat.getName())){
			rtype = ReportType.生产月报;
			SimpleDateFormat fmt = new SimpleDateFormat();
			fmt.applyPattern("yyyy年MM月 " + rtype.toString());
			ptitle = fmt.format(createDate);
			
		} else if ("产品合格率统计表".equals(cat.getName())){
			rtype = ReportType.产品合格率统计表;
			SimpleDateFormat fmt = new SimpleDateFormat();
			fmt.applyPattern("yyyy年  " + rtype.toString());
			ptitle = fmt.format(createDate);
		}
		new PDFConveter().convert(data, pdfname, fontHome, cat.getName(), "生产信息",ptitle, rtype);
	    NewsInfo bean = new NewsInfo();
		bean.setCreateDate(createDate);
		bean.setCatalog(catalog);
		bean.setName(ptitle);
		bean.setFullPath(path + name);
		bean.setWebPrefix(System.getProperty("base"));
		bean.setRelativeUrl(relativeUrl);
		return bean;
	}

	@Override
	public int countByCatalog(String catalog) throws DataAccessException {
		DBObject query = new BasicDBObject("catalog",catalog);
		return count(query);
	}

	@Override
	public void removeByCatalog(String catalog) {
		DBObject query = new BasicDBObject("catalog",catalog);
		collection.remove(query);		
	}



}